package com.yingxin.yx.framework.web.listener;



import com.google.common.collect.Maps;
import com.yingxin.yx.framework.commons.GlobalInstance;
import com.yingxin.yx.framework.commons.StatusCode;
import com.yingxin.yx.framework.commons.helper.JacksonHelper;
import com.yingxin.yx.framework.web.helper.ApplicationContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @author fanchao
 */
@Slf4j
@Component
public class StatusCodeLoadListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("===================================================");
        System.out.println(event.getApplicationContext().getDisplayName());
        if (event.getApplicationContext().getDisplayName().contains("FeignContext")) {
            return;
        }
        ApplicationContext applicationContext = event.getApplicationContext();
        log.info("加载SpringContext对象:" + applicationContext);
        ApplicationContextHelper.setContext(applicationContext);
       /* // base_code.json
        parseErrorCodeFileToMap("global-code.json");
        // codes.json
        BufferedReader bufferedReader = null;
        try {
            InputStream stream = this.getClass().getClassLoader().getResourceAsStream("codes.json");
            bufferedReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            List<String> codes = (List<String>) JacksonHelper.toList(stringBuilder.toString(), String.class);
            if (codes != null) {
                for (String code : codes) {
                    parseErrorCodeFileToMap(code);
                }
            }
        } catch (Exception e) {
            log.info("加载codes.json失败");
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }

    /**
     * 解析错误码数据放入内存当中
     */
    @SuppressWarnings("unchecked")
    private void parseErrorCodeFileToMap(String name) {
        log.info("开始解析" + name + "状态码数据.......");
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(
                    this.getClass().getClassLoader().getResourceAsStream(name), "UTF-8"));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            List<StatusCode> statusCodes = (List<StatusCode>) JacksonHelper.toList(stringBuilder.toString(), StatusCode.class);
            if (statusCodes == null) {
                return;
            }
            Map<String, StatusCode> map = Maps.newHashMap();
            for (StatusCode statusCode : statusCodes) {
                map.put(statusCode.getCode(), statusCode);
            }
            GlobalInstance.getInstance().getStatusCodeMap().putAll(map);
            log.info(name + "状态码数据:" + map);
        } catch (Exception e) {
            log.error("初始化" + name + "状态码数据失败:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    private void parseErrorCodeFileToMap(File file) {
        log.info("开始解析状态码数据.......");
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            List<StatusCode> statusCodes = (List<StatusCode>) JacksonHelper.toList(stringBuilder.toString(), StatusCode.class);
            if (statusCodes == null) {
                return;
            }
            Map<String, StatusCode> map = Maps.newHashMap();
            for (StatusCode statusCode : statusCodes) {
                map.put(statusCode.getCode(), statusCode);
            }
            GlobalInstance.getInstance().getStatusCodeMap().putAll(map);
            log.info("状态码数据:" + map);
        } catch (Exception e) {
            log.error("初始化状态码数据失败:" + e.getMessage());
            e.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /*
        URL url = this.getClass().getClassLoader().getResource("status_code.json");
        if (url != null) {
            parseErrorCodeFileToMap();
        } else {
            log.info("系统中不存在状态码配置文件信息");
        }
    */


    /*
        List<String> list = new ArrayList<>();
        list.add("code/base_code.json");
        list.add("code/customer_code.json");
        list.add("code/file_code.json");
        list.add("code/fund_code.json");
        list.add("code/menu_code.json");
        list.add("code/product_code.json");
        list.add("code/purchase_code.json");
        list.add("code/sale_code.json");
        list.add("code/stock_code.json");
        list.add("code/stock_document_code.json");
        list.add("code/supplier_code.json");
        list.add("code/tenant_code.json");
        list.add("code/warehouse_code.json");
        for (String item : list) {
            parseErrorCodeFileToMap(item);
        }
    */


    // InputStream ins = this.getClass().getClassLoader().getResourceAsStream(name);
    // if (ins == null) {
    //    return;
    // }
    // bufferedReader = new BufferedReader(new InputStreamReader(ins, "UTF-8"));

    // bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));

}
